#pragma once
#include <iostream>
#include <functional>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Protocol.hpp"
#include "Connection.hpp"
#include "NetCal.hpp"

using namespace log_ns;

class PackageParse
{
public:
    void Excute(Connection *conn)
    {
        while (true)
        {
            std::string package = Decode(conn->Inbuffer());
            if (package.empty())
                break;
            // 生成一个处理请求的指针
            auto req = Factory::BuildRequestDefault();
            std::cout << "package: \n"
                      << package << std::endl;
            // 反序列化
            req->Deserialize(package);
            // 业务处理
            auto resp = cal.Calculator(req);
            // 序列化应答
            std::string respjson;
            resp->Serialize(&respjson);
            std::cout << "respjson: \n"
                      << respjson << std::endl;
            // 添加长度报头
            respjson = Encode(respjson);
            std::cout << "respjson add header done: \n"
                      << respjson << std::endl;
            // 发回
            conn->AppendOutbuffer(respjson);
        }
        if (!conn->OutBuffer().empty())
            conn->_R->EnableConnectionReadWrite(conn->Sockfd(), true, true);
    }

private:
    NetCal cal; // 网络计算器
};